/*
 * Copyright (c) 2023. Shanghai HEADING information Engineering Co., Ltd. All rights reserved.
 */

package com.lovely602.boot.bootdemo.controller.java.thread;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lovely602.boot.bootdemo.controller.AbstractController;
import com.lovely602.boot.bootdemo.domain.common.RestResponse;
import com.lovely602.boot.bootdemo.filter.TokenContext;
import com.lovely602.boot.bootdemo.filter.TokenContextHolder;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lizhixing
 */
@Api(tags = "threadLocal服务")
@RestController
@RequestMapping(value = "/v1/bff/web/threadLocal", produces = "application/json;charset=utf-8")
@Slf4j
public class ThreadLocalController extends AbstractController {

  @GetMapping("{key}")
  @ApiOperation(value = "根据key获取值")
  public RestResponse<String> get(@PathVariable("key") String key) {
    TokenContext tokenContext = getTokenContext();
    String userId = null;
    if (tokenContext != null) {
      userId = tokenContext.getUserId();
    }
    log.info(Thread.currentThread().getName() + " userId :" + userId);
    return RestResponse.success(userId);
  }

  @PutMapping("{key}/{value}")
  @ApiOperation(value = "根据key设置值")
  public RestResponse<Void> set(@PathVariable("key") String key,
      @PathVariable("value") String value) {

    TokenContext tc = new TokenContext();
    tc.setUserId(value);
    TokenContextHolder.setTokenContext(tc);
    log.info(Thread.currentThread().getName() + " userId :" + value);
    return RestResponse.success();
  }

}
